package
{
	import flash.geom.Point;
	import flash.utils.getTimer;
	public  class Move
	{	
		private var _updateX:Number;
		private var _updateY:Number;
		private var _updateFunc:Function;
		private var _tempX:Number=0;
		private var _tempY:Number=0;
		private var _offsetX:Number;
		private var _offsetY:Number;
		private var _nowX:Number;
		private var _nowY:Number;
		private var _desX:Number;
		private var _desY:Number;
		private var _distance:Number;
		//private var _i;
		public function Move()
		{
		}
		
		
		public function goto(startPoint:Point,targetPoint:Point,speed:Number,func:Function):void
		{
			//TODO:计算每次tick移动的距离
			_tempX = 0;
			_tempY = 0;
			//_i = i;
			TickManager.instance.removeEventListener(TickEvent.TICK,gotoUpdateHandler);
			_distance = Point.distance(startPoint,targetPoint);
			_nowX = startPoint.x;
		 	_nowY = startPoint.y;
			_desX = targetPoint.x;
			_desY = targetPoint.y;
			_offsetX = Math.abs(_desX - _nowX);
			_offsetY = Math.abs(_desY - _nowY);
			if(_offsetX==0 && _offsetY==0) 
				return;
			//var temp:Number = Math.sqrt(_offsetX*_offsetX+_offsetY*_offsetY);
			var translatePoint:Point = Point.polar(speed, Math.atan(_offsetY/_offsetX));
			_updateX = ((_desX - _nowX)/_offsetX)*translatePoint.x;
			_updateY = ((_desY - _nowY)/_offsetY)*translatePoint.y;
			_updateFunc = func;
			TickManager.instance.addEventListener(TickEvent.TICK,gotoUpdateHandler);
		}
		
		private function gotoUpdateHandler(e:TickEvent):void
		{
			//var m:Number =  Math.abs(_updateX);
			//var n:Number =  Math.abs(_updateY);
			if(Math.abs(_tempX) + Math.abs(_updateX) > _offsetX || Math.abs(_tempY) + Math.abs(_updateY) > _offsetY)
			//var x=getTimer();
			//if(Math.sqrt(Math.pow(_tempX,2)+Math.pow(_tempY,2))+ Math.sqrt(Math.pow(_updateX,2)+Math.pow(_updateY,2)) >=_distance)
			{
				_updateFunc(_desX-(_nowX+_tempX),_desY-(_nowY+_tempY));
				TickManager.instance.removeEventListener(TickEvent.TICK,gotoUpdateHandler);
			}
			else
			{
				_tempX += _updateX;
				_tempY += _updateY;
				_updateFunc(_updateX,_updateY);
		
			}
			//trace(x-getTimer()+"\n");
		}
	}
}